<template>
  <div class="wh-100  d-flex fs-14" v-loading="loading">
    <!--左边-->
    <div  class="h-100 flex-1 w-0  py-12 px-12" style="background-color: #ffffff">
      <!--头部-->
      <div class="d-flex-between-center ch60" >
        <div>
          <Button type="primary" @click="handleAdd">添加市场</Button>
          <Button @click="handleDel(2)">批量删除</Button>
          <Button @click="importData">导入数据</Button>
          <Button @click="handleExportSelection">导出所选数据</Button>
          <Button @click="handleExportAll">导出全部数据</Button>
        </div>
        <div>
          <Button class="cw40" :icon="showRight ? `ios-arrow-forward` : `ios-arrow-back`" @click.native="showRight = !showRight" type="primary"></Button>
        </div>


      </div>
      <!--表格-->
      <div class=" bor-base-b ch01" >
        <!--数据-->
        <Table  class="mt-12" :columns="tableColumns" :data="tableData" @on-selection-change="selectChange">

          <template slot-scope="{ row, index }" slot="action">
            <a class="table-btn mr-12" @click="editData(row)">编辑</a>
            <a class="table-btn"  @click="deleteData(row)">删除</a>
          </template>
        </Table>
      </div>
      <!--分页-->
      <div class=" d-flex-center ch60" >
        <Page
            :current="searchForm.pageNumber"
            :total="total"
            :page-size="searchForm.pageSize"
            @on-change="changePage"
            @on-page-size-change="changePageSize"
            :page-size-opts="[10, 20, 50, 100, 200]"
            size="small"
            show-total
            show-elevator
            show-sizer
        ></Page>
      </div>
    </div>
    <!--右边-->
    <div class="h-100  ml-12 px-12 cw400" :class="!showRight ? 'hidden-table' : 'edit-table'" >
      <div class="bor-base-b ch02" >
        <div class="fw-6 d-flex ch60" style="align-items: center;">
          {{rightTitle}}
        </div>
        <div v-if="showType ==1 || showType == 2" class="ml-24 mr-12">
          <Form ref="formRef"
                :model="formValidate"
                :rules="ruleValidate"
                :label-width="labelWidth80">
            <FormItem label="市场代码" prop="submarketCode" v-if="showType === 1" :rules="[{ required: true, message: '市场代码不能为空', trigger: 'blur' }]">
              <Input v-model="formValidate.submarketCode" placeholder=""></Input>
            </FormItem>
            <FormItem label="市场代码" prop="submarketCode" v-if="showType === 2">
              <Input v-model="formValidate.submarketCode" placeholder="" disabled></Input>
            </FormItem>
            <FormItem label="市场名称" prop="submarketName" v-if="showType === 1" :rules="[{ required: true, message: '市场名称不能为空', trigger: 'blur' }]">
              <Input v-model="formValidate.submarketName" placeholder=""></Input>
            </FormItem>
            <FormItem label="市场名称" prop="submarketName" v-if="showType === 2">
              <Input v-model="formValidate.submarketName" placeholder="" disabled></Input>
            </FormItem>
            <FormItem label="所属院校" prop="schoolCode">
              <Select v-model="formValidate.schoolCode" @on-change="changeBackTask" clearable filterable placeholder="请选择所属院校">
                <Option v-for="(item,index) in schoolList" :value="item.code" :key="item.id">{{ item.name }}</Option>
              </Select>
            </FormItem>
            <FormItem label="市场所在地" prop="location">
              <Input v-model="formValidate.location" placeholder="输入详细地址"></Input>
            </FormItem>
            <FormItem label="排序值" prop="sort">
              <Input v-model="formValidate.sort" placeholder=""></Input>
            </FormItem>
          </Form>
        </div>
        <div v-if="showType == 3" class="ml-24 mr-12">
              <Form ref="formRef"
                    :model="formValidate"
                    :rules="ruleValidate"
                    :label-width="labelWidth80">
                  <FormItem label="市场代码" prop="submarketCode" >
                      <Input v-model="formValidate.submarketCode" placeholder="" ></Input>
                  </FormItem>
                  <FormItem label="市场名称" prop="submarketName" >
                      <Input v-model="formValidate.submarketName" placeholder="" ></Input>
                  </FormItem>
                  <FormItem label="所属院校" prop="schoolName">
                      <Select v-model="formValidate.schoolName" @on-change="changeBackTask" clearable filterable placeholder="请选择所属院校">
                          <Option v-for="(item,index) in schoolList" :value="item.name" :key="item.id">{{ item.name }}</Option>
                      </Select>
                  </FormItem>
                  <FormItem  prop="sort">
                      <Button  class="float-right" type="primary" @click="searchData">搜索</Button>
                      <Button  class="float-right"  @click="resetForm">重置</Button>
                  </FormItem>
              </Form>
          </div>

      </div>
      <div class="d-flex flex-row-reverse ch60" style="align-items: center;">
        <Button v-if="showType ==1 || showType == 2" class="float-right" type="primary" @click="handleSubmit">提交</Button>
        <Button v-if="showType ==1 || showType == 2" class="float-right" @click="handleCancel">取消</Button>
      </div>
    </div>
    <Modal
        v-model="importModalVisible"
        title="导入数据"
        :show-upload-list="true"
        :closable="false"
        :mask-closable="false"
    >
      <div class="d-flex flex-column py-12">
        <Upload
            ref="upload"
            action="#"
            :before-upload="beforeUpload"
            :format="['xlsx', 'xls']"
        >
          <Button icon="ios-cloud-upload-outline">上传文件</Button>
          <span class="ml-12">当前选择文件：{{ uploadfile.name }}</span>
        </Upload>
        <Button class="mt-12 cw160" type="primary" @click="downloadTemple" >下载模板</Button>
      </div>
      <div slot="footer">
        <Button type="text" @click="cancel">取消</Button>
        <Button type="primary" @click="uploadFile">确定</Button>
      </div>

    </Modal>
  </div>
</template>
<script>
import {
  addMarketDataAPI,
  delMarketDataByIdsAPI,
  exportBatchMarketDataAPI,
  exportAllMarketDataAPI,
  getMarketDataAPI,
  getSchoolDataAPI,
  updateMarketDataAPI, importMarketDataByIdsAPI, delByIdsMarketAccountAPI
} from "@/api/bys/marketManagement/marketManagement";
import {easyExcelImportData} from "@/api/bys/personInfo/bys";

export default {
  data() {
    return {
      labelWidth80: 80,
      height: 510,
      importModalVisible:false,
      loading: false,
      showRight: false,
      showType:3,
      rightTitle:'查询区',
      total:0,
      searchForm: {
        pageNumber: 1,
        pageSize: 10,
      },
      tableColumns:[],
      tableColumns_1: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '序号',
          type: 'index',
          width: 60,
          align: 'center'
        },
        {
          title: '市场代码',
          key: 'submarketCode',
          align: 'center'
        },
        {
          title: '市场名称',
          key: 'submarketName',
          align: 'center'
        },
        {
          title: '市场所在地',
          key: 'location',
          align: 'center'
        },
        {
          title: '所属院校',
          key: 'schoolName',
          align: 'center'
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center'
        }
      ],
      formFile:[],
      uploadfile: {},
      formDataA:'',
      tableData:[],
      formValidate: {
        submarketName: '',
        submarketCode: '',
        location: '',
        schoolCode: '',
        schoolName: '',
        sort: ''
      },
      ruleValidate: {
        // submarketName: [
        //   { required: true, message: '市场代码不能为空', trigger: 'blur' }
        // ],
        // submarketCode: [
        //   { required: true, message: '市场名称不能为空', trigger: 'blur' }
        // ],
      },
      ids:'',
      //院校列表
      schoolList:[],
      //table选中列表
      selectDataList:[]
    }
  },
  mounted() {
    this.onRestWindow()
    window.addEventListener('resize',this.onRestWindow)

    this.init()
  },
  beforeDestroy() {
    window.removeEventListener('resize',this.onRestWindow)
  },
  methods: {
      onRestWindow() {
          this.tableColumns = this.restTableCellWidth(this.tableColumns_1)
          this.labelWidth80 = this.searchLabelWidth(this.labelWidth80)
      },
      resetForm(){
          this.formValidate = {

          }
      },
      searchData(){
          this.searchForm.pageNumber = 1
          this.getMarketData()
      },
    init() {
      this.getMarketData()
      this.getSchoolList()
    },
    //获取数据
    getMarketData() {
      this.loading = true
      getMarketDataAPI({...this.searchForm,...this.formValidate}).then(res => {
        if (res.success) {
          this.tableData = res?.result?.records || []
          this.total = res?.result?.total || 0
          this.loading = false
          console.log(res.result,'市场信息')
        }else{
          this.loading = false
        }
      })
    },
    //获取院校列表
    getSchoolList() {
      this.loading = true;
      getSchoolDataAPI().then(res => {
        if (res.success) {
          // this.loading = false;
          this.schoolList = res.result;
        }
      });
    },
    changeBackTask(v) {

    },
    selectChange(selectdata){
      console.log(selectdata,'selectChange')
      this.selectDataList = selectdata
    },
    //添加账号
    handleAdd(){
      this.showRight = true
      this.rightTitle = '添加区'
      this.showType = 1
      this.formValidate = {
        submarketName: '',
        submarketCode: '',
        location: '',
        schoolCode: '',
        schoolName: '',
        sort: ''
      }
    },
    //批量删除
    handleDel(type){
      if (type == 1){
        this.$Modal.confirm({
          title: '确认删除',
          content: '您确认要删除该市场用户?',
          // loading: true,
          onOk: () => {
            delMarketDataByIdsAPI({ids:this.ids}).then(res => {
              if(res.success){
                this.$message.success(res.message)
                this.getMarketData()
              }
            })
          }
        });

      }
      if (type == 2){
          if (this.selectDataList.length == 0){
            this.$message.warning('您还未选择要删除的数据')
          }else{
            this.$Modal.confirm({
              title: '确认删除',
              content: '您确认要删除所选的 ' + this.selectDataList.length + ' 条数据?',
              // loading: true,
              onOk: () => {
                this.ids = this.selectDataList.map((obj)=>{return obj.id}).join(",");
                delMarketDataByIdsAPI({ids:this.ids}).then(res => {
                  if(res.success){
                    this.$message.success(res.message)
                    this.getMarketData()
                  }
                })
              }
            });

          }
      }


    },
    //重置用户密码
    handleResetPassword(){},
    beforeUpload(file) {
      console.log(file,'file')
      let formData = new FormData();
      this.uploadfile = file;
      console.log(this.uploadfile)
      const fileExt = file.name.split('.').pop().toLocaleLowerCase();
      if (fileExt == 'xlsx' || fileExt == 'xls' || fileExt == 'dbf' || fileExt == 'zip' || fileExt == 'rar') {
        formData.append('file', file);
        this.formDataA = formData
        return false
        // if (fileExt == "xlsx" || fileExt == "xls") {
      }
      },
    downloadTemple() {
      window.location.href = process.env.BASE_URL + '分市场基础信息导入模板.xlsx';
    },
    // 导入数据
    importData() {
      this.importModalVisible = true
    },
    cancel() {
      this.importModalVisible = false
      this.$refs.upload.clearFiles()
      this.uploadfile = ''
    },
    uploadFile(){
      // 发送请求给后端
      if (this.uploadfile){
        importMarketDataByIdsAPI(this.formDataA).then(res => {

          if (res.code === 200) {
            this.$Message.success(res.message);
            this.$refs.upload.clearFiles()
            this.uploadfile = ''
            this.importModalVisible = false
            this.getMarketData()
          } else if (res.code === 201) {
            this.$refs.upload.clearFiles()
            this.uploadfile = ''
            const byteArray = Uint8Array.from(atob(res.result), c => c.charCodeAt(0));
            const blob = new Blob([byteArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            // 创建临时 URL 对象
            const url = URL.createObjectURL(blob);
            const downloadLink = document.createElement('a');
            downloadLink.href = url;
            downloadLink.download = '导入失败数据汇总.xlsx'; // 设置文件名
            downloadLink.click();
          } else {
            this.$refs.upload.clearFiles()
            this.uploadfile = ''
            const byteArray = Uint8Array.from(atob(res.result), c => c.charCodeAt(0));
            const blob = new Blob([byteArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            // 创建临时 URL 对象
            const url = URL.createObjectURL(blob);
            const downloadLink = document.createElement('a');
            downloadLink.href = url;
            downloadLink.download = '导入失败数据汇总.xlsx'; // 设置文件名
            downloadLink.click();
          }
        })
      }else{
        this.$message.warning('请选择您要上传的文件')

      }

    },
    //导出所选数据
    handleExportSelection(){
      if (this.selectDataList.length == 0){
        this.$message.warning('您还未选择要导出的数据')
      }else {
        this.ids = this.selectDataList.map((obj) => {
          return obj.id
        }).join(",");
        exportBatchMarketDataAPI({ids: this.ids}).then((res) => {
          // type的格式可以可以设置，可以把appcation/json设置进去，然后设置导出的类型
          const blob = new Blob([res], {type: 'charset=utf-8'});
          let url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', '市场信息.xlsx');
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link); // 删除节点
          window.URL.revokeObjectURL(url); //释放该 url
        })
      }
    },
    //导出全部数据
    handleExportAll(){
      exportAllMarketDataAPI().then((res) => {
        // type的格式可以可以设置，可以把appcation/json设置进去，然后设置导出的类型
        const blob = new Blob([res], { type: 'charset=utf-8' });
        let url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', '市场信息.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); // 删除节点
        window.URL.revokeObjectURL(url); //释放该 url
      })
    },
    //删除
    deleteData(data) {
      console.log(data)
      this.ids = data.id
      this.handleDel(1)
    },
    //编辑
    editData(data) {
      this.showRight = true
      this.rightTitle = '编辑区'
      this.showType = 2
      this.formValidate = data
    },
    //提交
    handleSubmit(){

      this.$refs.formRef.validate(valid => {
        console.log(valid)
        console.log(123)
        if (valid) {
          console.log(this.schoolList,'this.schoolList')
          if (this.formValidate.schoolCode){
            let a= this.schoolList.filter(e => e.code == this.formValidate.schoolCode)
            console.log(a,'a')
            this.formValidate.schoolName = a[0].name
          }

          console.log(this.formValidate.schoolName,this.formValidate.schoolName)
          console.log(111111)
          if (this.showType == 1){
            console.log(222222)

            addMarketDataAPI(this.formValidate).then(res => {
              if (res.success) {
                this.showRight = false
                this.formValidate = {
                  submarketName: '',
                  submarketCode: '',
                  location: '',
                  schoolCode: '',
                  schoolName: '',
                  sort: ''
                }
                this.getMarketData()
                this.$message.success('添加成功！')

              }
            })
          }
          if (this.showType == 2){
            updateMarketDataAPI(this.formValidate).then(res => {
              if (res.success) {
                this.showRight = false
                this.formValidate = {
                  submarketName: '',
                  submarketCode: '',
                  location: '',
                  schoolCode: '',
                  schoolName: '',
                  sort: ''
                }
                this.getMarketData()
                this.$message.success('修改成功！')

              }
            })
          }

        }
      })
    },
    //取消
    handleCancel(){
      this.formValidate = {}
      // this.showRight = false
        this.showType = 3
        this.rightTitle = '查询区'
    },
    //分页
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.init()
    },
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.getMarketData()
      // this.getSchoolList()
    },
  }
}
</script>
<style scoped>
.edit-table {
  width: 330px;
  background-color: #fff;
}

.hidden-table {
  width: 0;
  display: none;
}

.ch60 {
  height: 60px
}
.cw40 {
  width: 40px
}
.ch01 {
  height: calc(100% - 120px)
}
.ch02 {
  height: calc(100% - 60px)
}
.cw400 {
  width: 400px;background-color: #ffffff
}
.cw160 {
  width: 160px
}
</style>
<style scoped lang="less">
// 重构样式
/deep/ .ivu-form-item-label{
    display: flex;
    justify-content: right;
    width: 150px !important;
}
/deep/ .ivu-form-item {
    width: 100%;
    margin-bottom: 0.1rem;
    margin-right: 0 !important;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
/deep/ .ivu-form-item-content {
    width: 100% !important;
    margin-left: 0 ! important;
}
/deep/ .ivu-select {
    width: 100% !important;
}
/deep/ .ivu-date-picker {
    width: 100% !important;
}
/deep/ .br {
    margin-top: 15px;
    bottom: 0.12rem !important;
    .ivu-form-item-content {
        display: flex;
    }
}
/deep/ .ivu-input-type-textarea,/deep/ .ivu-input {
    height: calc(100% - 7px) !important;
}
.flex-1 {
    height: 100%;
}
/deep/ .ivu-drawer-body {
    overflow: hidden;
    .d-flex-align-center {
        height: fit-content !important;
        margin-left: 0 !important;
        justify-content: right;
        box-sizing: border-box;
        padding-right: 7px;
    }
}
.box-key {
    /deep/ .ivu-form-item-content {
        margin-left: 100px !important;
    }
}
</style>